<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane label="仓库配置搜索">
        <avue-form :option="searchOption" v-model="query" @submit="searchChange" @reset-change="handleReset"></avue-form>
      </el-tab-pane>
    </el-tabs>

    <el-tabs type="border-card" style="margin: 20px 0" class="tab-font">
      <div class="btn-area">
        <el-button type="primary" icon="el-icon-plus" size="small" :disabled="!canAddWareHouse" @click="handleAddInfo('WAREHOUSE')">新建仓库</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" :disabled="!canAddArea" @click="handleAddInfo('STORAGE_AREA')">新建区域</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" :disabled="!canAddStorage" @click="handleAddInfo('STORAGE')">新建储位</el-button>
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
      </div>
      <el-tab-pane label="仓库配置明细">
        <el-table
          ref="table"
          v-loading="loading"
          :data="tableViewData"
          style="width: 100%"
          border
          size="small"
          :height="tableHeight"
          :max-height="tableHeight"
          class="custom-table"
          :row-style="{ height: `${rowHeight}px` }"
          :header-row-style="{ height: `${headerHeight}px` }"
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" width="50"> </el-table-column>
          <el-table-column prop="name" label="名称">
            <template slot-scope="scope">
              <!-- 计算缩进，如果有子节点代表还会多出一个展开图标，所以给无子节点的再加上展开图标的大小。 -->
              <div :style="{ 'margin-left': `${scope.row._level * 15}px` }">
                <!-- 自行实现树形表格的展开功能 -->
                <i
                  v-if="scope.row.hasChild > 0"
                  type="text"
                  :class="`${scope.row._isExpand ? 'el-icon-arrow-down' : 'el-icon-arrow-right'}`"
                  style="cursor: pointer"
                  @click="toggleExpand(scope.row, scope.$index)"
                ></i>
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="编码"></el-table-column>
          <el-table-column prop="levelName" label="等级"></el-table-column>
          <el-table-column prop="inventoryTypeName" label="仓库类型"></el-table-column>
          <el-table-column prop="inventorySubTypeName" label="子属性"></el-table-column>
          <el-table-column prop="workshopName" label="所属车间"></el-table-column>
          <el-table-column prop="areaTypeName" label="储位类型"></el-table-column>
          <el-table-column prop="isDefaultName" label="默认储位"></el-table-column>
          <el-table-column prop="color" label="颜色标识">
            <template slot-scope="{ row }">
              <i class="avue-crud__color color-icon" :style="{ 'background-color': row.color }"></i>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="启用">
            <template slot-scope="{ row }">
              {{ row.status === 1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="principalName" label="负责人"></el-table-column>
          <el-table-column prop="contacts" label="联系方式"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template slot-scope="{ row }">
              <el-button icon="el-icon-edit" type="text" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button icon="el-icon-view" type="text" size="small" @click="handleView(row)">详情</el-button>
              <el-button icon="el-icon-delete" type="text" size="small" @click="handleDelete(row)" :disabled="['SYSTEM_AREA'].includes(row.inventoryType)">删除</el-button>
              <el-button icon="el-icon-printer" type="text" size="small" @click="handlePrint(row)" v-if="row.areaType !== 'WAREHOUSE'">打印</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="avue-crud__pagination">
          <el-pagination
            :page-sizes="[15, 30, 50, 100]"
            background
            :current-page.sync="page.currentPage"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="sizeChange"
            @current-change="currentChange"
          >
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!--编辑-->
    <el-dialog v-if="addVisibile" :title="addDialogTitle" :visible.sync="addVisibile" append-to-body width="50%" @close="addVisibile = false" top="5vh">
      <div class="sail-header-dialog-content">
        <avue-form ref="editForm" :option="editOption" v-model="editForm" @submit="handleSubmit">
          <template slot="baseInfo">
            <div class="title">
              <i class="el-icon-vertical-bar avue-group__icon"></i>
              <h4>基础信息</h4>
            </div>
          </template>
          <template slot="shelf">
            <div class="title">
              <i class="el-icon-vertical-bar avue-group__icon"></i>
              <h4>智能料架信息</h4>
            </div>
          </template>
        </avue-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="saveData">保 存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--打印-->
    <el-dialog append-to-body title="打印机设置" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>打 印</span></el-button>
        <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!--导出-->
    <import-com :visible.sync="importConfig.show" @submit="handleLoadData"></import-com>

    <!--  详情-->
    <view-dialog v-if="visibile" :visibile.sync="visibile" :type="viewType" :row-data="viewData" @onCancel="handleConfirm"></view-dialog>

    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getData" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { filterEmptyValues, findAndAddChildren, findNodeById, flatTreeToList, flatTreeToListWithoutStatus, traverseTree } from '@/util/util';
import { add, getChildrenNode, getList, print, remove } from '@/api/warehouse/warehouseManagement';
import viewDialog from '@/views/warehouse/components/viewDialog';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { setEditOption } from '@/views/warehouse/productrefactor/warehouseManagement';

export default {
  name: 'warehouseManagement1',
  components: {
    CommonModalTemplate,
    viewDialog
  },
  data() {
    return {
      tableOption: {},
      visibile: false,
      viewType: '',
      addType: '',
      addDialogTitle: '',
      addVisibile: false,
      viewData: [],
      workshopList: [],
      timer: new Date().getTime(),
      editForm: {
        status: 1,
        materialAnalysisLevel: 'LOT_LEVEL'
      },
      editOption: {},
      searchOption: {
        menuSpan: 6,
        submitText: '搜索',
        submitIcon: 'el-icon-search',
        emptyText: '清空',
        emptyIcon: 'el-icon-delete',
        column: [
          {
            label: '名称',
            prop: 'name',
            span: 5
          },
          {
            label: '编码',
            prop: 'code',
            span: 5
          },
          {
            label: '仓库类型',
            prop: 'inventoryType',
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=inventory_type',
            span: 5
          }
        ]
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      importConfig: {
        show: false
      },
      query: {
        parentId: 0
      },
      printInfoModel: false,
      printInfo: {},
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      selectionList: [],
      loading: false,
      iconLoading: false,
      treeData: [],
      rowHeight: 40, // 表格每行的高度，用于计算定位
      headerHeight: 40, // 表格表头高度
      tableHeight: 350, // 表格最大高度
      tableData: [], // 转换成平行结构后的数据对象
      tableViewData: [], // 显示到界面的数据
      parentNameObj: {}, // name:parentName，用于通过名称找到父级名称
      treeDataObj: {}, // name:{...}，用于通过名称来找回原来的数据对象
      tableDataObj: {} // name:{...}，用于通过名称找到转换后的数据对象
    };
  },
  async mounted() {
    await this.onLoad(this.page);
    const data = flatTreeToList(this.treeData);
    this.tableData = data;
    this.initVirtualElement();
    this.updateViewData();
    // 添加滚动事件，滚动时再触发一次计算
    this.$refs.table.bodyWrapper.addEventListener('scroll', this.updateViewData);
  },
  beforeDestroy() {
    this.$refs.table.bodyWrapper.removeEventListener('scroll', this.updateViewData);
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    },
    canAddWareHouse() {
      return this.selectionList.length === 0;
    },
    canAddArea() {
      // 选择类型为仓库 或者区域
      return this.selectionList.length === 1 && ['STORAGE_AREA', 'WAREHOUSE'].includes(this.selectionList[0].areaType);
    },
    canAddStorage() {
      // 选择类型为区域
      return this.selectionList.length === 1 && this.selectionList[0].areaType === 'STORAGE_AREA';
    }
  },
  methods: {
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const res = await getList(page.currentPage, page.pageSize, Object.assign(params, filterEmptyValues(this.query)));
        const data = res.data.data;
        this.page.total = data.total;
        this.treeData = data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    parseTreeData(data = []) {
      const tableData = [];
      let index = 1;
      traverseTree(data, (i) => {
        // 转换成平行结构的对象
        const obj = {
          // 索引数，方便查看调试定位
          _levelNum: this.getLevelNum(i), // 层数，用于计算缩进
          _isExpand: false, // 默认不展开
          _isShow: true,
          _childrenNum: (i.children && i.children.length) || 0,
          _hasChildren: i.hasChild,
          ...i
        };
        tableData.push(obj);
        this.tableDataObj[i.name] = obj;

        this.treeDataObj[i.name] = i;

        index += 1;

        // 记录该节点的父级名称
        if (i.children && i.children.length > 0) {
          i.children.forEach((j) => {
            this.parentNameObj[j.name] = i.name;
          });
        }
      });
      this.tableData = tableData;
    },
    treeLoadData(tree, treeNode, resolve) {
      getChildrenNode({ parentId: tree.id }).then((res) => {
        const data = res.data.data;
        if (Array.isArray(data)) {
          data.forEach((item) => {
            if (item.hasChild) {
              item.hasChildren = true;
            }
          });
        }
        resolve(data || []);
      });
    },
    updateViewData() {
      // 根据是否展开来过滤掉不用显示的元素
      const tableViewData = this.tableData.filter((i) => i._isShow);

      // 计算是显示从第几行开始展示与结束
      const scrollTop = this.$refs.table.bodyWrapper.scrollTop;
      // let rowStartNum = Math.ceil(scrollTop / this.rowHeight);

      let rowStartNum = Math.max(0, Math.ceil(scrollTop / this.rowHeight));

      if (!this.showRowNum) {
        this.showRowNum = Math.ceil((this.tableHeight - this.headerHeight) / this.rowHeight);
      }
      // 最大的起始行
      console.log(`tableViewData.length=> ${tableViewData.length}`, `this.showRowNum=> ${this.showRowNum}`);

      if (rowStartNum > tableViewData.length - this.showRowNum) {
        // rowStartNum = tableViewData.length - this.showRowNum;
        rowStartNum = Math.max(0, tableViewData.length - this.showRowNum);
      }

      // // 最大的结束行
      // let rowEndNum = rowStartNum + this.showRowNum;
      // // let rowEndNum = Math.min(rowStartNum + this.showRowNum, tableViewData.length);
      // if (rowEndNum > tableViewData.length) {
      //   rowEndNum = tableViewData.length;
      // }
      let rowEndNum = Math.min(rowStartNum + this.showRowNum, tableViewData.length);
      console.log(`rowStartNum=> ${rowStartNum}  rowStartNum=>${rowEndNum}`);
      //   console.log('updateTableView row:', rowStartNum, '-', rowEndNum, ',', this.showRowNum, tableViewData.length);
      // 计算上下占位元素的高度
      // const top = rowStartNum * this.rowHeight + 'px'
      // const bottom = (tableViewData.length + 1 - rowEndNum)  * this.rowHeight + 'px'

      let top = Math.round(scrollTop) + 'px';
      const bottom = (tableViewData.length + 1 - rowEndNum) * this.rowHeight + 'px';
      // 如果到尾了，上占位达到最大高度
      console.log('-----', tableViewData.length - this.showRowNum);
      if (rowStartNum === tableViewData.length - this.showRowNum) {
        top = (tableViewData.length - this.showRowNum) * this.rowHeight + 'px';
      }
      console.log('top', top, 'bottom', bottom);
      // 调整占位元素的高度
      this.topElement.style.height = top;
      this.bottomElement.style.height = bottom;
      // 表格只显示要显示的行数内容
      this.tableViewData = tableViewData.slice(rowStartNum, rowEndNum).map((i) => ({ loading: false, ...i }));
    },
    getLevelNum(obj) {
      // 通过父级名称来计算该节点是第几层
      let result = 0;
      let parentName = obj.name;
      do {
        result += 1;
        parentName = this.parentNameObj[parentName];
      } while (parentName);
      return result;
    },
    // isShowByParentExpand(obj) {
    //   // 根据父级是否展开来判断 是否显示
    //   let flag = true;
    //   let parentName = this.parentNameObj[obj.name];
    //   while (flag && parentName) {
    //     const parent = this.tableDataObj[parentName];
    //     flag = !parent._isExpand;
    //     parentName = this.parentNameObj[parent.name];
    //   }
    //   return flag;
    // },
    async toggleExpand(row, index) {
      try {
        let isExpand = row._isExpand;
        //  找到初始树状结构中的对应节点
        const node = findNodeById(this.treeData, row.id);

        //  改变当前节点 展开状态
        node._isExpand = !isExpand;
        // this.treeData[index]._isExpand = !isExpand;
        if (!row.children || !row.children.length) {
          try {
            // 1 获取children
            const res = await getChildrenNode({ parentId: row.id });
            const data = res.data.data;
            // 4 遍历chidren 赋值 状态 并给他 树状结构添加子节点
            this.setTreeStatus(data, !isExpand, row._level);
            node.children = data;
            this.tableData = flatTreeToListWithoutStatus(this.treeData);
          } catch (e) {
            console.log(e);
          }
        } else {
          this.setTreeStatus(node.children, !isExpand);
          this.tableData = flatTreeToListWithoutStatus(this.treeData);
        }
        this.updateViewData();
      } catch (e) {
        console.log(e);
      }
    },
    setTreeStatus(children, status, level) {
      const travel = (list) => {
        list.forEach((child) => {
          // child._isExpand = false;
          child._isShow = status;
          child._level = child._level || level + 1;
          if (child.children && child.children.length) {
            // 展开则只展开子集中的isExpand为true的
            // 收拢则全部收拢
            if ((status && child._isExpand) || !status) travel(child.children);
          }
        });
      };
      travel(children);
    },
    initVirtualElement() {
      // 表格内部上下放两个占位元素，用于填充空间视图外的空间
      const tbody = this.$refs.table.bodyWrapper.firstChild;

      this.topElement = document.createElement('div');
      this.topElement.id = 'topElement';
      this.bottomElement = document.createElement('div');
      this.bottomElement.id = 'bottomElement';
      // 插入到最前面
      tbody.insertBefore(this.topElement, tbody.firstChild);
      // 插入到最后面
      tbody.appendChild(this.bottomElement);
    },
    async searchChange(form, done) {
      const queryParams = {
        code: form.code,
        name: form.name,
        inventoryType: form.inventoryType
      };
      const params = filterEmptyValues(queryParams);
      this.query = { parentId: 0, ...params };
      this.page.currentPage = 1;
      await this.refreshTableData();
      done();
    },
    async handleReset() {
      this.query = { parentId: 0 };
      await this.refreshTableData();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    async handleImport() {
      this.importConfig.show = true;
      // await this.refreshTableData();
    },
    async handleLoadData() {
      await this.refreshTableData();
    },
    handleAddInfo(type) {
      const titleMap = {
        WAREHOUSE: '新建仓库',
        STORAGE_AREA: '新建区域',
        STORAGE: '新建储位'
      };
      this.addType = type;
      this.addDialogTitle = titleMap[type];
      this.editOption = setEditOption(this);
      this.addVisibile = true;
    },
    async currentChange(currentPage) {
      this.page.currentPage = currentPage;
      await this.refreshTableData();
    },
    async sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      await this.refreshTableData();
    },
    handleView(row) {
      this.viewType = row.areaType;
      this.viewData = row;
      this.visibile = true;
    },
    handleDelete(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await remove(row.id);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          await this.refreshTableData();
        } catch (e) {
          console.warn(e);
        }
      });
    },
    handleConfirm(form) {
      this.visibile = false;
    },
    handlePrint(row) {
      this.printInfo.id = row.id;
      this.printInfo.name = row.name;
      this.printInfo.code = row.code;
      this.printInfoModel = true;
    },
    handleEdit(row) {
      const titleMap = {
        WAREHOUSE: '编辑仓库',
        STORAGE_AREA: '编辑区域',
        STORAGE: '编辑储位'
      };
      this.addType = row.areaType;
      this.addDialogTitle = titleMap[row.areaType];
      this.editOption = setEditOption(this);
      this.editForm = row;
      this.addVisibile = true;
    },
    /*
     * 打印
     */
    printSubmit() {
      this.$refs.printForm.validate((valid, done) => {
        if (valid) {
          let params = {
            name: this.printInfo.name,
            code: this.printInfo.code,
            id: this.printInfo.id,
            printId: this.printInfo.equipmentId,
            labelTemplateId: this.printInfo.labelTemplateId
          };
          print(params).then(
            (res) => {
              this.$refs.printForm.resetFields();
              this.printInfoModel = false;
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    getData(rowData) {
      switch (this.modalName) {
        case 'serialnoModal':
          this.editForm.sequenceDefinitionId = this._get(rowData, 'id', '');
          this.editForm.sequenceDefinitionName = this._get(rowData, 'name', '');
          this.$set(this.editForm, 'sequenceDefinitionId', this._get(rowData, 'id', ''));
          this.$set(this.editForm, 'sequenceDefinitionName', this._get(rowData, 'name', ''));
          break;
        case 'locationModal':
          this.editForm.locationId = this._get(rowData, 'id', '');
          this.editForm.locationName = this._get(rowData, 'name', '');
          break;
        case 'userModal':
          this.editForm.principal = this._get(rowData, 'id', '');
          this.editForm.principalName = this._get(rowData, 'name', '');
          break;
        case 'labelTemplateModal':
          this.$set(this.printInfo, 'labelTemplateId', rowData.id);
          this.$set(this.printInfo, 'labelTemplateName', rowData.fileName);
          break;
        case 'printersModal':
          this.$set(this.printInfo, 'equipmentId', rowData.id);
          this.$set(this.printInfo, 'equipmentName', rowData.name);
          break;
      }
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSerialnoCommonModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=SN',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '序列号规则名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '序列号规则编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '进制符',
            prop: 'hexString'
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },

    /**
     * 打开位置管理选择模态框
     */
    openLocationCommonModal() {
      this.modalName = 'locationModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择位置信息（双击进行选择）',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '国家',
            prop: 'country',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '省份',
            prop: 'province'
          },
          {
            label: '城市',
            prop: 'city'
          }
        ]
      };
    },
    /**
     * 打开用户管理选择模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?stauts=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    },
    saveData() {
      this.$refs.editForm.submit();
    },
    async handleSubmit(form, done) {
      console.log(form);
      try {
        const typeMap = {
          WAREHOUSE: 'WAREHOUSE',
          STORAGE_AREA: 'STORAGE_AREA',
          STORAGE: 'STORAGE'
        };
        const data = {
          areaType: typeMap[this.addType],
          ...form
        };
        if (typeMap[this.addType] !== 'WAREHOUSE' && !form.id) {
          data.parentId = this.selectionList[0].id;
        }
        await add(data);
        this.$message({
          type: 'success',
          message: `新增成功`
        });
        this.addVisibile = false;
        this.$refs.editForm.resetForm();
        this.editForm = {
          status: 1,
          materialAnalysisLevel: 'LOT_LEVEL'
        };
        this.refreshTableData();
      } catch (e) {
        console.log(e);
      } finally {
        done();
      }
    },
    handleCancel() {
      this.$refs.editForm.resetForm();
      this.editForm = {};
      this.addVisibile = false;
    },
    async refreshTableData() {
      await this.onLoad(this.page);
      const data = flatTreeToList(this.treeData);
      this.tableData = data;
      this.updateViewData();
    }
  }
};
</script>

<style scoped lang="scss">
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}

.custom-table {
  ::v-deep thead {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
  }
}
::v-deep .el-table th,
.el-table tr {
  background-color: #fafafa;
}
.btn-area {
  min-height: 40px;
  height: auto;
  margin-bottom: 5px;
}
.color-icon {
  height: 30px;
  width: 30px;
}

.title {
  display: flex;
  align-items: center;
  height: 20px;
}
</style>
